<?php
namespace app\common\validate\tysj;

class SetInventory extends Base {
    /**
     * 验证规则
     */
    protected $rule = [
        'uid'       => 'require',
        'ids'       => 'require|isMatch|isUsers:tysj\\ProductSpecs',
        'values'    => 'require|isNum|inventorys',
        'inventory' => 'require|egt:0'
    ];

    /**
     * 提示消息
     */
    protected $message = [
        'uid'               => '用户ID不能为空',
        'ids.require'       => 'ids不能为空',
        'ids.isMatch'       => 'ids和values不匹配',
        'values.require'    => 'values不能为空',
        'values.isNum'      => 'values不合法',
        'values.inventorys' => '库存不足',
        'inventory.egt'     => '库存不足'
    ];
    
    /**
     * 验证场景
     */
    protected $scene = [
        'update'   => ['uid', 'ids', 'values'],
        'over'     => ['inventory']
    ];

    //id和值是否匹配
    protected function isMatch($value, $rule, $data = []) {   
        return is_array($data['ids']) && is_array($data['values']) && count($data['ids']) == count($data['values']);
    }

    //传入的值是否是数字
    protected function isNum($values, $rule, $data = []) {
        foreach ($values as $k => $value) {
            if(!is_numeric($value) || intval($value) != $value) {
                return false;
                break;
            }
        }
        return true;
    }

    //库存
    protected function inventorys($values, $rule, $data = []) {
        $ids = $data['ids'];
        foreach($values as $k => $value) {
            $row = loadOnly('Model')->lockFind('tysj\\ProductSpecs', $ids[$k]);
            if(empty($row)) {
                return false;
            }
            if($row['inventory'] + $value < 0) {
                return $ids[$k] . $this->message['values.inventorys'];
            }
        }
        return true;
    }
}
